package com.bbcare.followup.plat.service.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

import com.bbcare.department.plat.service.IDepartmentBasicService;
import com.bbcare.department.plat.service.impl.DepartmentBasicService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.comm.*;
import com.bbcare.followup.plat.entity.*;
import com.bbcare.followup.plat.store.ibatis.IContentTemplDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientSwitchDao;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.IPatientSwitchService;
import com.bbcare.followup.plat.task.TaskComparator;
import com.bbcare.switchData.entity.model.FuQueueInfo;


@Service
public class PatientSwitchService implements IPatientSwitchService {
    private final Log logger = LogFactory.getLog(PatientSwitchService.class);

    @Autowired
    private IPatientSwitchDao patientSwitchDao;
    @Autowired
    private IPatientTaskContentDAO taskContentDAO;
    @Autowired
    private IPatientTaskDAO patientTaskDao;
    @Autowired
    private IContentTemplDAO contentTemplDao;
    @Autowired
    private IPatientTaskContentDAO patientTaskConDao;

    @Autowired
    private IDepartmentBasicService departmentBasicService;

    @Autowired
    private IPatientService patientService;


    @Override
    public List<FollowQueue> getQueueList(String patientId) {
        List<FollowQueue> list = patientSwitchDao.getQueueList(patientId);
        return list;
    }

    @Override
    public Patient getPatientInfo(String patientId) throws  Exception {
        Map<String,Object> map = new HashMap();
        map.put("userId",patientId);
        return patientService.getPatient(map);
    }

    @Override
    public String getJoinQueueName(String patientId) {
        Set<String> names = new HashSet<>();
        List<FuQueueInfo> list =  patientSwitchDao.getJoinQueue(patientId);
        list.forEach(i->{
            if(i!=null && i.getQueueName()!=null){
                names.add(i.getQueueName());
            }
        });
        if(names.size()==0){
            return null;
        }
        return ToolUtils.listToString( new ArrayList<String>(names));
    }

    @Override
    public Map<String, Object> getPatientQuestion(String patientId) throws Exception {
        Map<String, Object> questionMap = new HashMap<>();
        Patient patient = getPatientInfo(patientId);
        //科研编号
        questionMap.put("Pub12x00008","");
        questionMap.put("Pub1100001",patient.getPhoneNo());
        questionMap.put("Pub1100002",patient.getUserName());
        questionMap.put("Pub1100003",patient.getGender());
        questionMap.put("Pub1100004",patient.getBirthday());
        questionMap.put("Pub1100005",patient.getExpectedDay());
        questionMap.put("Pub1100006",patient.getPregnancyDay());
        return questionMap;
    }

    @Override
    public String getPatientTask(HashMap<String, Object> paramMap) {
        return patientSwitchDao.getPatientTask(paramMap);
    }

    @Override
    public void updatePreCheckStatus(String userId, String tenantId,String queueId,String deptId) throws Exception {
        String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();
        if(!queueId.contains("-YZDL")){
            patientSwitchDao.updatePreCheckStatus(userId,tenantId);
            // type=14 患者患者队列状态
            int type = 14;
            // system=1 2.0系统
            int system = 1;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type",type);
            jsonObject.put("userId",userId);
            jsonObject.put("tenantId",tenantId);
            jsonObject.put("system",system);
            jsonObject.put("platType",platType);
            jsonObject.put("deptId",deptId);
            if (StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl")))  {
                //如果config.properties中有redirectUrl配置项，才会发送请求。没有配置项，就不发送了。
                HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl") ,jsonObject.toJSONString());
            }
        }

    }

    @Override
    public void setExistQueue(Map<String, Object> retMap) {
        List<Map<String, Object>> pqsList  = (List<Map<String, Object>>) retMap.get("rows");
        for (Map item:  pqsList) {
            item.put("existQueue",getJoinQueueName(item.get("patientId").toString()));
        }
    }

/*---------------------------------------------------------------------------*/
    private void insertBody3ToTarget(final String targetTaskId, final String tenantId, final String userId, final String queueId, final String ptSchemeId, Map<String,String> contentMap) {
        final String updateTime = DateUtil.getSysDateA();
        final String updateAccept = UUID.randomUUID().toString().replaceAll("-", "");
        List<PatientContentData> ptcInList = new ArrayList<>();
        for (Map.Entry<String, String> entry : contentMap.entrySet()) {
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            PatientContentData pcdVo = new PatientContentData();
            pcdVo.setContentId("");
            pcdVo.setCreateTime(updateTime);
            pcdVo.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
            pcdVo.setQuestionId(mapKey);
            pcdVo.setQuestionAnswer(mapValue);
            pcdVo.setTaskId(targetTaskId);
            pcdVo.setUpdateAccept(updateAccept);
            pcdVo.setUpdateTime(updateTime);
            pcdVo.setUpdateType(Constants.UPDATE_TYPE_INSERT);
            pcdVo.setUserId(userId);
            pcdVo.setPtSchemeid(ptSchemeId);
            pcdVo.setTemplType("0");
//            pcdVo.setOpTime(opTime);
            pcdVo.setQueueId(queueId);
            pcdVo.setTenantId(tenantId);
            pcdVo.setSourceTypeCreate("2");
            pcdVo.setSourceTypeUpdate("2");
            ptcInList.add(pcdVo);
        }
        try {
            taskContentDAO.savePatientTaskContentDataBatch(ptcInList);
        } catch (Exception ex)  {
            logger.error(ex.getMessage());
        }
    }

    /**
     * 更新建档任务中的体格3项数据。
     * @param targetTaskId 目标队列的建档任务ID.
     * @param srcTaskId 原始队列数据。
     */
    private void updateDataForJDTask(final String srcTaskId, final String targetTaskId, final String tenantId, final String userId, final String targetQueueId, final String targetSchemeId)    {
        String questionId,questionAnswer;
        List<PatientContentData> contentDataList = null;
        Map<String,Object> paraMap  = new HashMap<>();
        paraMap.put("taskId", srcTaskId);
        try {
            contentDataList = taskContentDAO.selectContentDataByTaskId(paraMap);
        } catch (Exception ex)  {
            logger.error(ex.getMessage());
        }
        Map<String,String> contentMap  = new HashMap<>();
        if (null == contentDataList || contentDataList.isEmpty())   {
            logger.warn("----updateDataForJDTask() source data is EMPTY!");
        } else {
            for(PatientContentData data : contentDataList) {
                questionId  = data.getQuestionId();
                questionAnswer  = data.getQuestionAnswer();
                if (questionId.equalsIgnoreCase("zcejd_cstz") && !StringUtils.isEmpty(questionAnswer)) {
                    contentMap.put("zcejd_cstz", questionAnswer);
                    contentMap.put("jd_cstz", questionAnswer);
                }
                if (questionId.equalsIgnoreCase("zcejd_cssc") && !StringUtils.isEmpty(questionAnswer)) {
                    contentMap.put("zcejd_cssc", questionAnswer);
                    contentMap.put("jd_cssc", questionAnswer);
                }
                if (questionId.equalsIgnoreCase("zcejd_cstw") && !StringUtils.isEmpty(questionAnswer)) {
                    contentMap.put("zcejd_cstw", questionAnswer);
                    contentMap.put("jd_cstw", questionAnswer);
                }

                if (questionId.equalsIgnoreCase("jd_cstz") && !StringUtils.isEmpty(questionAnswer)) {
                    contentMap.put("zcejd_cstz", questionAnswer);
                    contentMap.put("jd_cstz", questionAnswer);
                }
                if (questionId.equalsIgnoreCase("jd_cssc") && !StringUtils.isEmpty(questionAnswer)) {
                    contentMap.put("zcejd_cssc", questionAnswer);
                    contentMap.put("jd_cssc", questionAnswer);
                }
                if (questionId.equalsIgnoreCase("jd_cstw") && !StringUtils.isEmpty(questionAnswer)) {
                    contentMap.put("zcejd_cstw", questionAnswer);
                    contentMap.put("jd_cstw", questionAnswer);
                }
            }
        }

        insertBody3ToTarget(targetTaskId, tenantId, userId, targetQueueId, targetSchemeId, contentMap);  //保存到关联队列建档任务中的出生体格3项。
    }

    /**
     * 关联队列时，复制宝宝的建档体格数据。
     * @param srcTaskId 原始队列建档任务ID。
     * @param targetDataMap 关联的目标队列。
     * @return
     */
    @Override
    public Map<String,Object> copyPatientFuData(final String srcTaskId, final Map<String,Object> targetDataMap) {
        final String tenantId   = targetDataMap.get("tenantId").toString();
        final String patientId  = targetDataMap.get("patientId").toString();
        final String targetQueueId    = targetDataMap.get("queueId").toString();
        final String targetSchemeId   = targetDataMap.get("ptSchemeId").toString();
        logger.info("++++copyPatientFuData() tenantId:"+tenantId+", queueId:"+targetQueueId+", patientId:"+patientId+", schemeId:"+targetSchemeId);
        //先找目标队列的task_id。
        List<Object> taskList = null;
        Map<String, Object> taskParaMap = new HashMap<>();
        taskParaMap.put("userId",       patientId);
        taskParaMap.put("ptSchemeId",   targetSchemeId);
        taskParaMap.put("queueId",      targetQueueId);
        taskParaMap.put("currDate", DateUtil.getCurrDate2());
        try {
            taskList = patientService.qryPatientTaskList(taskParaMap);
        } catch (Exception ex)  {
            logger.error(ex.getMessage());
        }
        Object seqNoObj = null;
        if (null != taskList)   {
            //找到了该宝宝的随访任务。
            for(Object taskObj : taskList)   {
                Map<String,Object> taskMap  = (Map<String,Object>)taskObj;
                seqNoObj    = taskMap.get("seqNo");
                if (null == seqNoObj || !(seqNoObj instanceof Integer))   {
                    logger.warn("----copyPatientFuData() seqNo is NULL or !instanceof Integer!");
                    break;
                }
                Integer seqNo   = (Integer) taskMap.get("seqNo");
                if (0 == seqNo.intValue())  {
                    //这是目标队列的建档任务，修改该任务中的体格3项数据。
                    final String targetTaskId = taskMap.get("taskId").toString();
                    updateDataForJDTask(srcTaskId, targetTaskId, tenantId, patientId, targetQueueId, targetSchemeId);
                    break;
                }
            }
        }

        Map<String,Object> retMap   = new HashMap<>();
        return retMap;
    }
/*---------------------------------------------------------------------------*/

/*母乳分析仪对接处理。---------------------------------------------------------------------------*/
    @Autowired
    private JdbcTemplate jdbc;

    @Autowired
    private NamedParameterJdbcTemplate namedJdbc;

    /**
     * 查询宝宝详情。
     * @param key 手机和姓名的模糊查询。
     * @return
     */
    @Override
    public List<Map<String,String>> queryBaby(final String key) {
        final String sql    = "SELECT id, user_name, phone_no, gender, DATE_FORMAT(birthday,'%Y-%m-%d') AS birthday FROM pt_user_info WHERE tenant_id='gzykdxfsdsyyta001' AND user_name LIKE '%" + key + "%' OR phone_no LIKE '%" + key + "%' AND id IN (SELECT DISTINCT(user_id) FROM pt_queuescheme_info WHERE user_status='1')";
        logger.info("++++queryBaby() sql is:"+sql);
        List<Map<String,String>> rowList   = jdbc.query(sql, new RowMapper<Map<String,String>>(){
            public Map<String,String> mapRow(ResultSet rs, int rowNum) throws SQLException {
                Map<String,String> row = new HashMap<String,String>();
                row.put("guid",     rs.getString("id"));
                row.put("cardid",   rs.getString("id"));
                row.put("phone",    rs.getString("phone_no"));
                row.put("name",     rs.getString("user_name"));
                row.put("sex",      (true==rs.getString("gender").equalsIgnoreCase("N"))?"男":"女");
                row.put("birthday", rs.getString("birthday"));
                return row;
            }
        });

        return rowList;
    }

    /**
     * 备份接收到的母乳分析仪JSON数据。
     * @param jsonData
     * @return
     */
    public String backupMilkData(JSONObject jsonData) {
        final String backupSql   = "INSERT INTO pt_breast_milk_his (id,content) VALUES (:id,:content)";
        Map<String,Object> paraMap  = new HashMap<>();
        final String id = UUID.randomUUID().toString();
        paraMap.put("id",       id);
        paraMap.put("content",  jsonData.toJSONString());
        int insRet = 0;
        try {
            insRet = this.namedJdbc.update(backupSql, paraMap);
        } catch (DataAccessException dae)   {
            logger.error(dae.getMessage());
            return null;
        }
        logger.info("++++backupMilkData() insertRet:"+insRet);
        if (1 == insRet)    {
            return id;
        } else {
            return null;
        }
    }

    /**
     * 更新母乳数据。
     * @param paraMap(userId,zcey_mrfx_mrlx,fat,protein,lactose,energy,mineral,moisture,density)
     * 检测时间：zcey_jcsj
     * 母乳类型：zcey_mrfx_mrlx
     * 初乳|脂肪：   zcey_cr_zfjcz
     * 初乳|蛋白质： zcey_cr_dbzjcz
     * 初乳|乳糖：   zcey_cr_rtjcz
     * 初乳|能量：   zcey_cr_nljcz
     * 初乳|矿物质： zcey_cr_kwzjcz
     * 初乳|水分：   zcey_cr_sfjcz
     * 初乳|密度：   zcey_cr_mdjcz
     *
     * 过渡乳|脂肪： zcey_gdr_zfjcz
     *
     * 成熟乳|脂肪： zcey_csr_zfjcz
     *
     * 晚乳|脂肪： zcey_wr_zfjcz
     */
    public int updateMilkData(final Map<String,String> paraMap)    {
        logger.info("++++updateMilkData() is called.");
        final String userId = paraMap.get("userId");
        //查询高危儿队列宝宝今天的随访任务ID。
        final String taskSql= "SELECT id FROM pt_task_info WHERE user_id='"+userId+"' AND queue_id='12gzykdxfsdsyyqueue001' AND finish_date=CURDATE()";
        List<Map<String,String>> taskList   = jdbc.query(taskSql, new RowMapper<Map<String,String>>(){
            public Map<String,String> mapRow(ResultSet rs, int rowNum) throws SQLException {
                Map<String,String> row = new HashMap<String,String>();
                row.put("taskId",   rs.getString("id"));
                return row;
            }
        });
        if (taskList.isEmpty() || 1 != taskList.size()) {
            logger.error("----updateMilkData() baby "+userId+" has no task OR more tasks today!");
            return 0;
        }

        final String taskId = taskList.get(0).get("taskId");
        logger.info("++++updateMilkData() baby "+userId+" has a task today.");
        final String milkTime   = DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd_HH_mm_ss);
        final String mrlx   = paraMap.get("zcey_mrfx_mrlx");
        String fatName = "zcey_cr_zfjcz", proteinName="zcey_cr_dbzjcz", lactoseName="zcey_cr_rtjcz", energyName="zcey_cr_nljcz",
                mineralName="zcey_cr_kwzjcz", moistureName="zcey_cr_sfjcz", densityName="zcey_cr_mdjcz",jgfxName="zcey_cr_jgfx",zdjyName="zcey_cr_zdjy";
        if (mrlx.equals("过渡乳"))    {
            fatName     = "zcey_gdr_zfjcz";
            proteinName = "zcey_gdr_dbzjcz";
            lactoseName = "zcey_gdr_rtjcz";
            energyName  = "zcey_gdr_nljcz";
            mineralName = "zcey_gdr_kwzjcz";
            moistureName= "zcey_gdr_sfjcz";
            densityName = "zcey_gdr_mdjcz";
            jgfxName    = "zcey_gdr_jgfx";
            zdjyName    = "zcey_gdr_zdjy";
        } else if (mrlx.equals("成熟乳"))    {
            fatName     = "zcey_csr_zfjcz";
            proteinName = "zcey_csr_dbzjcz";
            lactoseName = "zcey_csr_rtjcz";
            energyName  = "zcey_csr_nljcz";
            mineralName = "zcey_csr_kwzjcz";
            moistureName= "zcey_csr_sfjcz";
            densityName = "zcey_csr_mdjcz";
            jgfxName    = "zcey_csr_jgfx";
            zdjyName    = "zcey_csr_zdjy";
        } else if (mrlx.equals("晚乳"))    {
            fatName     = "zcey_wr_zfjcz";
            proteinName = "zcey_wr_dbzjcz";
            lactoseName = "zcey_wr_rtjcz";
            energyName  = "zcey_wr_nljcz";
            mineralName = "zcey_wr_kwzjcz";
            moistureName= "zcey_wr_sfjcz";
            densityName = "zcey_wr_mdjcz";
            jgfxName    = "zcey_wr_jgfx";
            zdjyName    = "zcey_wr_zdjy";
        }
        final String fatFieldName = fatName, proteinFieldName=proteinName, lactoseFieldName=lactoseName, energyFieldName=energyName,
                mineralFieldName=mineralName, moistureFieldName=moistureName, densityFieldName=densityName,jgfxFieldName=jgfxName,zdjyFieldName=zdjyName;

        int[] updRet = null;
        final String fat        = paraMap.get("fat");
        final String protein    = paraMap.get("protein");
        final String lactose    = paraMap.get("lactose");
        final String energy     = paraMap.get("energy");
        final String mineral    = paraMap.get("mineral");
        final String moisture   = paraMap.get("moisture");
        final String density    = paraMap.get("density");
        final String jgfx       = paraMap.get("jgfx");
        final String zdjy       = paraMap.get("zdjy");
        updRet = jdbc.batchUpdate("UPDATE pt_contentdata_info SET question_answer = ? WHERE question_id = ? AND user_id = ? AND task_id = ?",
            new BatchPreparedStatementSetter()  {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setString(3, userId);   //user_id.
                    ps.setString(4, taskId);   //task_id.
                    switch (i)  {
                        case 0:
                            ps.setString(1, milkTime);          //question_answer.
                            ps.setString(2, "zcey_jcsj");   //question_id.
                            break;
                        case 1:
                            ps.setString(1, mrlx);
                            ps.setString(2, "zcey_mrfx_mrlx");
                            break;
                        case 2:
                            ps.setString(1, fat);
                            ps.setString(2, fatFieldName);
                            break;
                        case 3:
                            ps.setString(1, protein);
                            ps.setString(2, proteinFieldName);
                            break;
                        case 4:
                            ps.setString(1, lactose);
                            ps.setString(2, lactoseFieldName);
                            break;
                        case 5:
                            ps.setString(1, energy);
                            ps.setString(2, energyFieldName);
                            break;
                        case 6:
                            ps.setString(1, mineral);
                            ps.setString(2, mineralFieldName);
                            break;
                        case 7:
                            ps.setString(1, moisture);
                            ps.setString(2, moistureFieldName);
                            break;
                        case 8:
                            ps.setString(1, density);
                            ps.setString(2, densityFieldName);
                            break;
                        case 9:
                            ps.setString(1, jgfx);
                            ps.setString(2, jgfxFieldName);
                            break;
                        case 10:
                            ps.setString(1, zdjy);
                            ps.setString(2, zdjyFieldName);
                            break;
                    }
                }
                @Override
                public int getBatchSize() {
                    return 11;
                }
            });

        if (null != updRet && 11 == updRet.length)   {
            for(int i : updRet)   {
                if (1 != i) {
                    return 0;
                }
            }
            return 1;
        } else {
            return 0;
        }
    }
/*---------------------------------------------------------------------------*/

    /**
     * GY3Y的需求：查询患者当前选中的随访任务中的曾有诊断，该诊断来源于前序随访任务中的当前诊断和曾有诊断。
     * @param selectedTaskId 当前选中的随访任务
     * @return 曾有诊断
     * @throws Exception
     */
    public Map<String,Object> queryCyzd(final String selectedTaskId) throws Exception {
        logger.info("++++queryCyzd() selectedTaskId:"+selectedTaskId);
        Map<String,Object> retMap   = new HashMap<>();
        String querySql   = "SELECT user_id, pt_schemeid, queue_id FROM pt_task_info WHERE id='"+selectedTaskId+"'";
        List<Map<String,Object>> rowlist    = jdbc.queryForList(querySql);
        final String patientId  = rowlist.get(0).get("user_id").toString();
        final String schemeId   = rowlist.get(0).get("pt_schemeid").toString();
        final String queueId    = rowlist.get(0).get("queue_id").toString();
        Map<String,Object> paraMap = new HashMap<>();
        paraMap.put("ptSchemeId",   schemeId);
        paraMap.put("taskFlag",     "1");
        List<Object> taskList  = patientService.qryPatientTaskList(paraMap);
        final int size  = taskList.size();
        if (size<2) {
            retMap.put("cyzd",  "");
            return retMap;
        }

        Collections.sort(taskList, new TaskComparator());    //重新排序这些随访任务。
        Map<String,Object> taskRefMap   = null;
        int i,j,selectIdx=size-1;
        for(i=1; i!=size; i++)  {
            taskRefMap = (Map)taskList.get(i);
            if (!taskRefMap.get("taskId").equals(selectedTaskId))    {
                continue;
            } else {
                //当前选中的随访任务索引i。
                selectIdx   = i;
                break;
            }
        }
        String taskId, mqzd="",cyzd="";
        String retCyzd  = "",finishDate;
        for(j=selectIdx-1; j!=0; j--)   {
            taskRefMap  = (Map)taskList.get(j);
            taskId      = taskRefMap.get("taskId").toString();
            finishDate  = taskRefMap.get("finishDate").toString();
            if (StringUtils.isNotBlank(finishDate))    {
                //这是前序已完成的随访任务，查询问卷中的诊断。
                querySql= "SELECT question_answer FROM pt_contentdata_info WHERE question_id='zcey_mqzd' AND task_id='" + taskId +"' AND user_id='" + patientId + "' AND pt_schemeid='" + schemeId + "'" ;
                rowlist = jdbc.queryForList(querySql);
                if (0 != rowlist.size())    {
                    mqzd= rowlist.get(0).get("question_answer").toString();
                }
                querySql= "SELECT question_answer FROM pt_contentdata_info WHERE question_id='zcey_cyzd' AND task_id='" + taskId +"' AND user_id='" + patientId + "' AND pt_schemeid='" + schemeId + "'" ;
                rowlist = jdbc.queryForList(querySql);
                if (0 != rowlist.size())    {
                    cyzd= rowlist.get(0).get("question_answer").toString();
                }
                if (StringUtils.isNotBlank(mqzd))  {
                    //该随访有【目前诊断】。
                    retCyzd = finishDate + "：" + mqzd;
                }
                if (StringUtils.isNotBlank(cyzd))  {
                    //该随访有【曾有诊断】。
                    retCyzd = StringUtils.isBlank(retCyzd)?(finishDate+"："):(retCyzd+"；") + mqzd;
                }
                if (StringUtils.isNotBlank(retCyzd))    {
                    break;
                }
            }
        }

        logger.info("++++queryCyzd() retCyzd:"+retCyzd);
        retMap.put("cyzd",      retCyzd);
        retMap.put("ptSchemeId",schemeId);
        retMap.put("userid",    patientId);
        return retMap;
    }

    /**
     * 处理广医三院的【曾有诊断】。
     * @param paraMap
     * @param taskId
     * @throws Exception
     */
    @Override
    public Map<String,Object> dealGy3yContent(Map<String, Object> paraMap, final String taskId) throws Exception {
        Map<String,Object> retMap   = new HashMap<>();
        List<PatientContentData> answers    = (List<PatientContentData>)paraMap.get("PtContentdataInfo");
        if (null == answers || 0 == answers.size()) {
            retMap.put("msg",  "本随访任务没有问卷！");
            return retMap;
        }

        boolean auto    = true; //是否需要自动化曾有诊断。
        String cyzd = "";
        for(PatientContentData answer : answers)   {
            if (answer.getQuestionId().equals("zcey_cyzd") && StringUtils.isNotBlank(answer.getQuestionAnswer()))   {
                retMap.put("msg",  "本随访任务问卷中的曾有诊断已填写了。");
                return retMap;
            }
        }
        //自动化曾有诊断。
        if (auto) {
            final Map<String,Object> cyzdMap    = queryCyzd(taskId);
            final String autoCyzd   = cyzdMap.get("cyzd").toString();
            if (StringUtils.isNotBlank(autoCyzd)) {
                if (!paraMap.containsKey("values"))   {
                    paraMap.put("values", new HashMap<String,Object>());
                }
                Map<String,Object> values   = (Map<String,Object>)paraMap.get("values");
                values.put("zcey_cyzd", autoCyzd);
                values.put("zcru_cyzd", autoCyzd);
                retMap.put("msg",  "本随访任务问卷中的曾有诊断未填写，系统自动化为："+autoCyzd);
            } else {
                retMap.put("msg",  "本随访任务的前序任务中没有诊断信息！");
            }
        }

        return retMap;
    }


    /**
     * 简明随访病历。
     * @param paraMap
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryAllAnswerByPatient(final Map<String, Object> paraMap) throws Exception {
        HashMap<String, Object> argMap = new HashMap<String, Object>(paraMap);
        HashMap<String, Object> retOut = new HashMap<String, Object>();
        String conTemplVerId = (String) argMap.get("conTemplVerId");
//        String ptSchemeId = (String) argMap.get("ptSchemeId");
//        String tenantId = (String) argMap.get("tenantId");
//        String patientId = (String) argMap.get("patientId");

        Map<String, Object> templMap = new HashMap<String, Object>();
        templMap.put("id", conTemplVerId);
        final List<ContentTemplVersion> ctvList = contentTemplDao.selectContentTemplById(templMap);
        if (null == ctvList || 0 == ctvList.size()) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPL_NOT_EXIST, "任务内容模板版本为空！");
        }

        argMap.put("taskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);// 暂时只展示门诊任务
        List<HashMap<String, Object>> retList = patientTaskDao.selectTaskByPtSchemeIdAndTempl(argMap);
        if (null == ctvList || 0 == ctvList.size()) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_TASK_NOT_EXIST, "患者下无此任务相关内容！");
        }
        int it=0,k=0,i=0;
        String questionId,questionAnswer;
        Map<String,String> questionMap  = new HashMap<>();  //保存所有填写的问卷答案。
        for (it = 0; it < retList.size(); it++) {
            HashMap<String, Object> taskInfoMap = retList.get(it);
            HashMap<String, Object> quesInputMap = new HashMap<String, Object>();
            // 先根据taskId+templType查询问卷答案，若无答案，则根据taskId查询问卷答案记录
            quesInputMap.put("taskId", taskInfoMap.get("taskId"));
            quesInputMap.put("contDataTemplType", taskInfoMap.get("templType"));
            List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(quesInputMap);
            if (CollectionUtils.isEmpty(ptTaskConList)) {
                quesInputMap.put("contDataTemplType", null);
                ptTaskConList = patientTaskConDao.selectContentDataByTaskId(quesInputMap);
            }

            Map<String, Object> quesOutMap = new HashMap<String, Object>();
            if (!CollectionUtils.isEmpty(ptTaskConList)) {
                for (k=0; k < ptTaskConList.size(); k++) {
                    PatientContentData contentVo    = ptTaskConList.get(k);
                    questionAnswer  = contentVo.getQuestionAnswer();
                    if (StringUtils.isNotEmpty(questionAnswer)) {
                        questionId  = contentVo.getQuestionId();
                        quesOutMap.put(questionId, questionAnswer);
                        questionMap.put(questionId, questionAnswer);
                    }
                }
            }

            taskInfoMap.put("values", quesOutMap);
        }

        //重新排序这些随访任务。
        Collections.sort(retList, new TaskComparator());
        retOut.put("tasks", retList);

        final ContentTemplVersion templ = ctvList.get(0);
        JSONArray jsonArr   = JSON.parseArray(templ.getTemplData());
        final int jsonSize  = jsonArr.size();
        Map<String,Object> jsonMap,contentMap;
        Object idObj;
        JSONArray idArr;
        boolean remove  = false;
        for(k=0; k!=jsonSize; k++)  {
            jsonMap = jsonArr.getJSONObject(k);
            JSONArray children = (JSONArray)jsonMap.get("children");
            int childrenSize  = children.size();
            for(i=0; i!=childrenSize; i++)   {
                contentMap  = children.getJSONObject(i);
                remove  = false;
                if (contentMap.containsKey("id"))   {
                    idObj   = contentMap.get("id");
                    if (idObj instanceof String)    {
                        questionId  = idObj.toString();
                        if (!questionMap.containsKey(questionId))   {
                            remove  = true;
                        } else {
                            questionAnswer  = questionMap.get(questionId);
                            if (StringUtils.isBlank(questionAnswer))    {
                                remove  = true;
                            } else {
                                if (questionAnswer.equals("未见异常") || questionAnswer.equals("请选择"))  {
                                    remove  = true;
                                }
                            }
                        }
                    } else if (idObj instanceof JSONArray)    {
                        idArr   = (JSONArray)idObj;
                    }
                }

                if (remove)    {
                    //这个questionId是不需要返回的。
                    children.remove(i);
                    i--;
                    childrenSize--;
                }
            }
        }
        retOut.put("questionnaireData", jsonArr);

        return retOut;
    }

}
